package internal

import (
	"GameServer/Common/data"
	"GameServer/Common/utils"
	"GameServer/Game/errors"
	"GameServer/Game/m"
	"GameServer/Game/sp"
	"fmt"

	"github.com/globalsign/mgo/bson"
	log "github.com/sirupsen/logrus"
)

// 公会，发送 玩家发送红包消息
func (this *UnionManager) UnionSendRedPacketMsg(us *m.User, ext *m.ChatExt, broadcastFunc func(uid string, data interface{})) (chatMsg *m.ChatMsg, err error) {
	v, ok := m.Cache.Get("unionMembers", us.UnionId)
	if !ok {
		err = errors.NewErrcode(data.Errcode.NoUnion, fmt.Sprintf("公会成员获取失败,id:%s", us.UnionId))
		return
	}
	mMembers := v.(*m.UnionMembers)
	members := mMembers.MemberList()
	uid := us.Uid.Hex()
	mid := bson.NewObjectId().Hex()

	nowUnix := utils.TNow().Unix()

	extStr := ext.String()
	chatMsg = &m.ChatMsg{
		Mid:  mid,
		Uid:  uid,
		Time: nowUnix,
		Ext:  extStr,
		Type: ext.Type,
	}
	err = m.AddUnionChatMsg(mMembers.UnionId, chatMsg)
	if err != nil {
		log.WithFields(log.Fields{
			"method": "UnionChat",
			"data":   chatMsg,
		}).Error(err)
	}

	bData := &sp.ChatNoticeRequest{
		Mid:         mid,
		Uid:         uid,
		Name:        us.Name,
		Head:        us.Head,
		Channel:     1,
		Time:        nowUnix,
		AvatarFrame: us.AvatarFrame,
		Ext:         extStr,
	}
	utils.AsyncFunc(func() {
		for _, item := range members {
			if item.Uid == uid {
				continue
			}
			broadcastFunc(item.Uid, bData)
		}
	})
	return
}

// 公会发送红包
func (this *UnionManager) UnionSendRedPacket(us *m.User, ext *m.ChatExt, broadcastFunc func(uid string, data interface{})) (chatMsg *m.ChatMsg, err error) {
	v, ok := m.Cache.Get("unionMembers", us.UnionId)
	if !ok {
		err = errors.NewErrcode(data.Errcode.NoUnion, fmt.Sprintf("公会成员获取失败,id:%s", us.UnionId))
		return
	}
	mMembers := v.(*m.UnionMembers)
	members := mMembers.MemberList()
	uid := us.Uid.Hex()
	mid := bson.NewObjectId().Hex()
	nowUnix := utils.TNow().Unix()

	extStr := ext.String()
	chatMsg = &m.ChatMsg{
		Mid:  mid,
		Uid:  uid,
		Time: nowUnix,
		Ext:  extStr,
		Type: ext.Type,
	}

	err = m.AddUnionChatMsg(mMembers.UnionId, chatMsg) // 公会聊天信息，添加玩家发送的红包消息
	if err != nil {
		log.WithFields(log.Fields{
			"method": "UnionChat",
			"data":   chatMsg,
		}).Error(err)
	}

	bData := &sp.ChatNoticeRequest{
		Mid:         mid,
		Uid:         uid,
		Name:        us.Name,
		Head:        us.Head,
		Channel:     1,
		Time:        nowUnix,
		Ext:         extStr,
		AvatarFrame: us.AvatarFrame,
	}
	utils.AsyncFunc(func() {
		for _, item := range members {
			broadcastFunc(item.Uid, bData)
		}
	})
	return
}
